import { reactive } from 'vue'
import { syncAPI } from '../api/sync.js'
import { useTodoStore } from './todoStore.js'
import storageAPI from '@/api/storage'

const syncState = reactive({
  lastSyncTime: null,
  isSyncing: false,
  syncError: null,
  syncSuccess: false,
  autoSyncEnabled: true,
  intervalSyncEnabled: false,
  syncInterval: 15 // 默认15分钟
})

// 定时同步定时器
let intervalTimer = null
// 自动同步定时器（软件运行期间每15分钟同步）
let autoSyncTimer = null

// 异步初始化同步状态
const initSyncState = async () => {
  try {
    const lastSyncTime = await storageAPI.getItem('lastSyncTime')
    const intervalSyncEnabled = await storageAPI.getItem('intervalSyncEnabled')
    const syncInterval = await storageAPI.getItem('syncInterval')
    const autoSyncEnabled = await storageAPI.getItem('autoSyncEnabled')
    
    syncState.lastSyncTime = lastSyncTime
    syncState.intervalSyncEnabled = intervalSyncEnabled === 'true' || intervalSyncEnabled === true
    syncState.syncInterval = syncInterval ? parseInt(syncInterval) : 15
    syncState.autoSyncEnabled = autoSyncEnabled !== 'false' // 默认启用
    
    // 如果启用了定时同步，启动定时器
    if (syncState.intervalSyncEnabled) {
      startIntervalSync()
    }
    
    // 如果启用了自动同步，启动自动同步定时器
    if (syncState.autoSyncEnabled) {
      startAutoSync()
    }
    
    // 软件启动时进行一次同步
    if (syncState.autoSyncEnabled) {
      setTimeout(() => {
        autoSync()
      }, 2000) // 延迟2秒，确保应用完全加载
    }
  } catch (error) {
    console.warn('初始化同步状态失败:', error)
  }
}

// 检测版本冲突
const autoResolveConflicts = (serverTasks) => {
  const todoStore = useTodoStore()
  const resolvedTasks = []
  
  console.log('🔍 开始自动解决版本冲突:', {
    serverTasksCount: serverTasks.length,
    localTasksCount: todoStore.state.tasks.length
  })
  
  serverTasks.forEach(serverTask => {
    const taskId = serverTask.client_id || serverTask.id
    const localTask = todoStore.state.tasks.find(task => 
      String(task.id) === String(taskId)
    )
    
    if (localTask) {
      const serverVersion = parseInt(serverTask.version) || 1
      const localVersion = parseInt(localTask.version) || 1
      const serverTime = new Date(serverTask.last_modified_at || serverTask.updated_at)
      const localTime = new Date(localTask.updatedAt)
      
      console.log(`🔍 检查任务 ${taskId}:`, {
        title: localTask.title,
        serverVersion,
        localVersion,
        serverTime: serverTime.toISOString(),
        localTime: localTime.toISOString(),
        serverNewer: serverVersion > localVersion,
        localModifiedLater: localTime > serverTime
      })
      
      // 自动选择updatedAt最新的版本
      if (serverVersion !== localVersion) {
        const useServerVersion = serverTime > localTime
        
        if (useServerVersion) {
          console.log(`📥 自动选择服务器版本 (更新时间: ${serverTime.toISOString()}):`, {
            taskId,
            title: serverTask.title,
            reason: '服务器修改时间更新'
          })
          
          // 直接更新本地任务为服务器版本
          const taskIndex = todoStore.state.tasks.findIndex(task => 
            String(task.id) === String(taskId)
          )
          
          if (taskIndex > -1) {
            todoStore.state.tasks[taskIndex] = {
              ...todoStore.state.tasks[taskIndex],
              title: serverTask.title,
              text: serverTask.text,
              notes: serverTask.notes || '',
              completed: serverTask.completed,
              priority: serverTask.priority,
              listId: serverTask.listId || serverTask.list_id,
              dueDate: serverTask.due_date || serverTask.dueDate,
              startTime: serverTask.start_time || serverTask.startTime,
              status: serverTask.status,
              pomodoroRequired: serverTask.pomodoro_required || serverTask.pomodoroRequired,
              pomodoroCount: serverTask.pomodoro_count || serverTask.pomodoroCount,
              pomodoroCompleted: serverTask.pomodoro_completed || serverTask.pomodoroCompleted,
              completed_at: serverTask.completed_at,
              repeatType: serverTask.repeat_type || serverTask.repeatType,
              recurrence: serverTask.recurrence,
              version: serverTask.version,
              recurring_series_id: serverTask.recurring_series_id,
              created_from_task_id: serverTask.created_from_task_id,
              is_recurring_parent: serverTask.is_recurring_parent,
              deleted_at: serverTask.deleted_at,
              updatedAt: serverTask.last_modified_at || serverTask.updated_at
            }
          }
        } else {
          console.log(`📤 保持本地版本 (更新时间: ${localTime.toISOString()}):`, {
            taskId,
            title: localTask.title,
            reason: '本地修改时间更新'
          })
          
          // 确保本地版本号高于服务器版本号，以便在下次同步时更新服务器
          const taskIndex = todoStore.state.tasks.findIndex(task => 
            String(task.id) === String(taskId)
          )
          
          if (taskIndex > -1 && localVersion <= serverVersion) {
            const newVersion = serverVersion + 1
            console.log(`📤 递增本地任务 ${taskId} 版本号:`, {
              oldVersion: localVersion,
              serverVersion,
              newVersion
            })
            
            todoStore.state.tasks[taskIndex] = {
              ...todoStore.state.tasks[taskIndex],
              version: newVersion,
              updatedAt: new Date().toISOString()
            }
          }
        }
        
        resolvedTasks.push({
          taskId,
          resolution: useServerVersion ? 'server' : 'local',
          serverTime: serverTime.toISOString(),
          localTime: localTime.toISOString()
        })
      } else if (localVersion > serverVersion) {
        console.log(`📤 本地任务 ${taskId} 版本更新，将同步到服务器:`, {
          title: localTask.title,
          localVersion,
          serverVersion
        })
      } else if (serverVersion > localVersion) {
        console.log(`📥 服务器任务 ${taskId} 版本更新，将更新本地:`, {
          title: localTask.title,
          serverVersion,
          localVersion
        })
      }
    } else {
      console.log(`📝 服务器任务 ${taskId} 在本地不存在，将直接添加`)
    }
  })
  
  console.log('🔍 自动冲突解决完成:', {
    resolvedTasksCount: resolvedTasks.length,
    resolvedTasks
  })
  
  return resolvedTasks
}

// 解决冲突
// resolveConflicts函数已移除，因为现在使用autoResolveConflicts自动解决冲突

// 立即初始化
initSyncState()

export const useSyncStore = () => {
  const todoStore = useTodoStore()
  
  // 立即同步
  const syncNow = async () => {
    if (syncState.isSyncing) return
    
    try {
      syncState.isSyncing = true
      syncState.syncError = null
      
      // 生成客户端ID（用于标识本次同步请求）
      const clientId = `web_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      // 准备本地数据（包含所有数据，包括已删除的）
      const localData = {
        client_id: clientId,
        lists: todoStore.state.lists
          .map(list => {
            // 处理color字段，将CSS变量转换为实际颜色值
            let color = list.color
            if (color && color.startsWith('var(')) {
              color = '#6366f1' // 默认颜色
            }
            
            return {
              id: list.id.toString(),
              name: list.name,
              color: color,
              last_modified_at: list.updatedAt || list.createdAt,
              deleted_at: list.deleted_at || null
            }
          }),
        tasks: (() => {
          // 去重处理：确保client_id唯一
          const uniqueTasks = []
          const seenClientIds = new Set()
          
          todoStore.state.tasks.forEach(task => {
            const clientId = task.id.toString()
            
            // 如果client_id已存在，跳过这个任务
            if (seenClientIds.has(clientId)) {
              console.warn('发现重复的任务ID，跳过:', {
                clientId,
                title: task.title,
                duplicateTask: task
              })
              return
            }
            
            seenClientIds.add(clientId)
            uniqueTasks.push({
              client_id: clientId,
              title: task.title,
              text: task.text,
              notes: task.notes || '',
              completed: task.completed,
              priority: task.priority,
              listId: task.listId ? task.listId.toString() : '',
              dueDate: task.dueDate,
              startTime: task.startTime,
              status: task.status,
              pomodoroRequired: task.pomodoroRequired,
              pomodoroCount: task.pomodoroCount,
              pomodoroCompleted: task.pomodoroCompleted,
              completed_at: task.completed_at || null, // 添加完成时间字段
              repeat_type: task.repeatType || null, // 添加重复类型字段
              recurrence: task.recurrence || null, // 添加重复规则字段
              version: task.version || 1, // 添加版本号
              recurring_series_id: task.recurring_series_id || null, // 重复任务系列ID
              created_from_task_id: task.created_from_task_id || null, // 创建来源任务ID
              is_recurring_parent: task.is_recurring_parent || false, // 是否为重复任务父任务
              last_modified_at: task.updatedAt || task.createdAt,
              deleted_at: task.deleted_at || null
            })
          })
          
          console.log('同步任务去重处理:', {
            原始任务数: todoStore.state.tasks.length,
            去重后任务数: uniqueTasks.length,
            重复任务数: todoStore.state.tasks.length - uniqueTasks.length
          })
          
          return uniqueTasks
        })()
      }
      
      // 执行同步
      const result = await syncAPI.syncAll(localData)
      
      // 更新本地数据
      if (result.success) {
        // 自动解决版本冲突
        const resolvedTasks = autoResolveConflicts(result.data.tasks || [])
        
        console.log('🔄 自动冲突解决完成，继续合并数据:', {
          resolvedTasksCount: resolvedTasks.length
        })
        
        // 合并数据（冲突已自动解决）
        todoStore.mergeSyncData(result.data)
        
        // 更新同步时间
        syncState.lastSyncTime = new Date().toISOString()
        await storageAPI.setItem('lastSyncTime', syncState.lastSyncTime)
        
        // 设置同步成功状态
        syncState.syncSuccess = true
        setTimeout(() => {
          syncState.syncSuccess = false
        }, 3000) // 3秒后隐藏成功提示
      }
      
      return result
    } catch (error) {
      console.error('同步失败:', error)
      syncState.syncError = error.message
      throw error
    } finally {
      syncState.isSyncing = false
    }
  }
  
  // 自动同步
  const autoSync = async () => {
    if (!syncState.autoSyncEnabled || syncState.isSyncing) return
    
    try {
      await syncNow()
    } catch (error) {
      console.warn('自动同步失败:', error)
    }
  }
  
  // 启动自动同步定时器（软件运行期间每15分钟同步）
  const startAutoSync = () => {
    stopAutoSync() // 先停止现有定时器
    
    if (syncState.autoSyncEnabled) {
      const intervalMs = 15 * 60 * 1000 // 15分钟
      autoSyncTimer = setInterval(async () => {
        if (!syncState.isSyncing) {
          try {
            await syncNow()
            console.log('自动同步完成（15分钟定时）')
          } catch (error) {
            console.warn('自动同步失败:', error)
          }
        }
      }, intervalMs)
      console.log('自动同步定时器已启动，间隔: 15分钟')
    }
  }
  
  // 停止自动同步定时器
  const stopAutoSync = () => {
    if (autoSyncTimer) {
      clearInterval(autoSyncTimer)
      autoSyncTimer = null
      console.log('自动同步定时器已停止')
    }
  }
  
  // 设置自动同步
  const setAutoSync = async (enabled) => {
    syncState.autoSyncEnabled = enabled
    
    // 保存到本地存储
    try {
      await storageAPI.setItem('autoSyncEnabled', enabled.toString())
    } catch (error) {
      console.warn('保存自动同步设置失败:', error)
    }
    
    if (enabled) {
      startAutoSync()
    } else {
      stopAutoSync()
    }
  }
  
  // 清除同步错误
  const clearSyncError = () => {
    syncState.syncError = null
  }
  
  // 格式化同步时间
  const formatSyncTime = (timestamp) => {
    if (!timestamp) return '从未同步'
    const now = new Date()
    const syncDate = new Date(timestamp)
    const diffMs = now - syncDate
    const diffMins = Math.floor(diffMs / 60000)
    
    if (diffMins < 1) return '刚刚'
    if (diffMins < 60) return `${diffMins}分钟前`
    if (diffMins < 1440) return `${Math.floor(diffMins / 60)}小时前`
    return syncDate.toLocaleDateString()
  }
  
  // 启动定时同步
  const startIntervalSync = () => {
    stopIntervalSync() // 先停止现有定时器
    
    if (syncState.intervalSyncEnabled && syncState.syncInterval > 0) {
      const intervalMs = syncState.syncInterval * 60 * 1000 // 转换为毫秒
      intervalTimer = setInterval(async () => {
        if (!syncState.isSyncing) {
          try {
            await syncNow()
            console.log('定时同步完成')
          } catch (error) {
            console.warn('定时同步失败:', error)
          }
        }
      }, intervalMs)
      console.log(`定时同步已启动，间隔: ${syncState.syncInterval}分钟`)
    }
  }
  
  // 停止定时同步
  const stopIntervalSync = () => {
    if (intervalTimer) {
      clearInterval(intervalTimer)
      intervalTimer = null
      console.log('定时同步已停止')
    }
  }
  
  // 设置定时同步
  const setIntervalSync = async (enabled, interval = 15) => {
    syncState.intervalSyncEnabled = enabled
    syncState.syncInterval = interval
    
    // 保存到本地存储
    try {
      await storageAPI.setItem('intervalSyncEnabled', enabled.toString())
      await storageAPI.setItem('syncInterval', interval.toString())
    } catch (error) {
      console.warn('保存定时同步设置失败:', error)
    }
    
    if (enabled) {
      startIntervalSync()
    } else {
      stopIntervalSync()
    }
  }

  return {
    syncState,
    syncNow,
    autoSync,
    clearSyncError,
    formatSyncTime,
    startIntervalSync,
    stopIntervalSync,
    setIntervalSync,
    startAutoSync,
    stopAutoSync,
    setAutoSync
  }
}